package org.nimi317.web_gis.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.nimi317.web_gis.form.post.Page;
import org.nimi317.web_gis.utils.Convert;
import org.nimi317.web_gis.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息
 * 注意： 必须在网关通过请求头的方法传入，同时在HeaderInterceptor拦截器设置值。 否则这里无法获取
 *
 * @author ruoyi
 */
public class SecurityContextHolder {
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return StringUtils.cast(map.getOrDefault(key, null));
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }


    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static String getTableName() {
        return get("tableName", String.class);
    }

    public static void setTableName(String value) {
        set("tableName", value);
    }

    public static void setTableName(List<String> value) {
        String s = value.stream().map(String::trim).collect(Collectors.joining(","));
        set("tableName", s);
    }

    public static void setClassWithDivision(String[] value) {
        set("classWithDivision", value);
    }

    public static String[] getClassWithDivision() {
        return get("classWithDivision", String[].class);
    }

    public static void setLastTime(LocalDateTime lastUpdateTime) {
        set("lastUpdateTime", lastUpdateTime);
    }

    public static LocalDateTime getLastTime() {
        return get("lastUpdateTime", LocalDateTime.class);
    }

    public static void setPageSize(Page page) {
        set("pageSize", page);
    }


    public static Page getPageSize() {
        return get("pageSize", Page.class);
    }
}
